// 1. React核心库
import React, { useState } from 'react';

// 2. UI组件库 - 按字母顺序排列
import {
  Card,
  Row,
  Col,
  Button,
  Space,
  message,
} from 'antd';

// 3. 图标库
import {
  SaveOutlined,
  CloseOutlined,
  ArrowLeftOutlined,
  UserAddOutlined,
} from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer, ProForm, ProFormText, ProFormSwitch } from '@ant-design/pro-components';

// 5. 工具库
import { history } from '@umijs/max';

// 6. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 7. 生成的类型定义 (必须使用，禁止手工定义)
import type { UserCreateRequest } from '@/services/generated/src/index';

const UserCreate: React.FC = () => {
  const [createLoading, setCreateLoading] = useState(false);

  // 创建用户
  const handleCreate = async (values: UserCreateRequest) => {
    try {
      setCreateLoading(true);
      await autoLoginInDev();

      const response = await apiClients.users.usersCreate({
        userCreateRequest: values
      });

      console.log('🚀 创建用户API响应:', response);

      // 🔑 关键：手动提取data字段（不使用useRequest，无自动dataField处理）
      const responseData = (response as any).data || response;

      message.success('用户创建成功');
      history.push('/users/list');
      return responseData;
    } catch (error) {
      message.error('用户创建失败');
      throw error;
    } finally {
      setCreateLoading(false);
    }
  };

  return (
    <PageContainer
      header={{
        title: '创建用户',
        breadcrumb: {
          items: [
            { title: '首页' },
            { title: '用户管理' },
            { title: '用户列表', path: '/users/list' },
            { title: '创建用户' },
          ],
        },
        extra: [
          <Button
            key="back"
            icon={<ArrowLeftOutlined />}
            onClick={() => history.back()}
          >
            返回
          </Button>,
        ],
      }}
    >
      <Row gutter={24}>
        <Col span={16} offset={4}>
          <Card 
            title={
              <Space>
                <UserAddOutlined />
                创建新用户
              </Space>
            }
          >
            <ProForm
              onFinish={async (values) => {
                await handleCreate(values as UserCreateRequest);
              }}
              submitter={{
                render: (props) => (
                  <Row justify="center">
                    <Space size="large">
                      <Button
                        size="large"
                        onClick={() => history.back()}
                        icon={<CloseOutlined />}
                      >
                        取消
                      </Button>
                      <Button
                        type="primary"
                        size="large"
                        loading={createLoading}
                        onClick={() => props.form?.submit?.()}
                        icon={<SaveOutlined />}
                      >
                        创建用户
                      </Button>
                    </Space>
                  </Row>
                ),
              }}
            >
              <Row gutter={16}>
                <Col span={12}>
                  <ProFormText
                    name="username"
                    label="用户名"
                    placeholder="请输入用户名"
                    rules={[
                      { required: true, message: '请输入用户名' },
                      { min: 3, message: '用户名长度至少3位' },
                      { max: 150, message: '用户名长度不能超过150位' },
                      { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线' },
                    ]}
                  />
                </Col>
                <Col span={12}>
                  <ProFormText
                    name="email"
                    label="邮箱"
                    placeholder="请输入邮箱地址"
                    rules={[
                      { required: true, message: '请输入邮箱' },
                      { type: 'email', message: '请输入有效的邮箱地址' },
                    ]}
                  />
                </Col>
              </Row>

              <Row gutter={16}>
                <Col span={12}>
                  <ProFormText
                    name="first_name"
                    label="名字"
                    placeholder="请输入名字"
                    rules={[
                      { required: true, message: '请输入名字' },
                      { max: 30, message: '名字长度不能超过30位' },
                    ]}
                  />
                </Col>
                <Col span={12}>
                  <ProFormText
                    name="last_name"
                    label="姓氏"
                    placeholder="请输入姓氏"
                    rules={[
                      { required: true, message: '请输入姓氏' },
                      { max: 30, message: '姓氏长度不能超过30位' },
                    ]}
                  />
                </Col>
              </Row>

              <Row gutter={16}>
                <Col span={12}>
                  <ProFormText.Password
                    name="password"
                    label="密码"
                    placeholder="请输入密码"
                    rules={[
                      { required: true, message: '请输入密码' },
                      { min: 8, message: '密码长度至少8位' },
                      { 
                        pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{8,}$/,
                        message: '密码必须包含大小写字母和数字，长度至少8位'
                      },
                    ]}
                  />
                </Col>
                <Col span={12}>
                  <ProFormText.Password
                    name="password_confirm"
                    label="确认密码"
                    placeholder="请再次输入密码"
                    dependencies={['password']}
                    rules={[
                      { required: true, message: '请确认密码' },
                      ({ getFieldValue }) => ({
                        validator(_, value) {
                          if (!value || getFieldValue('password') === value) {
                            return Promise.resolve();
                          }
                          return Promise.reject(new Error('两次输入的密码不一致'));
                        },
                      }),
                    ]}
                  />
                </Col>
              </Row>

              <Row gutter={16}>
                <Col span={12}>
                  <ProFormSwitch
                    name="is_active"
                    label="是否激活"
                    tooltip="激活的用户可以正常登录系统"
                    initialValue={true}
                  />
                </Col>
                <Col span={12}>
                  <ProFormSwitch
                    name="is_staff"
                    label="管理员权限"
                    tooltip="管理员可以访问后台管理界面"
                    initialValue={false}
                  />
                </Col>
              </Row>
            </ProForm>
          </Card>
        </Col>
      </Row>
    </PageContainer>
  );
};

export default UserCreate;
